import { Injectable } from '@nestjs/common'
import { CreateWilleDto } from './dto/create-wille.dto'
import { UpdateWilleDto } from './dto/update-wille.dto'
import axios from 'axios'
import Cheerio from 'cheerio'
import * as fs from 'fs'
import { join } from 'path'

@Injectable()
export class WillesService {
  create(createWilleDto: CreateWilleDto) {
    return 'This action adds a new wille'
  }

  async findAll() {
    let index = 1
    const urls: string[] = []
    const getCosPlay = async () => {
      console.log(index)
      await axios.get(`https://www.ciyuanjie.cn/cosplay/page${index === 0 ? '' : `_${index}`}.html`).then(async (res) => {
        //console.log(res.data)
        const $ = Cheerio.load(res.data)
        const pageNext = $('.next.page-numbers').length
        if (pageNext) {
          $('#index_ajax_list li .cardImage').each(function () {
            urls.push($(this).attr('data-original'))
          })
          console.log('%c [ urls ]-29', 'font-size:13px; background:#be1ee1; color:#ff62ff;', urls)

          index++
          await getCosPlay()
        }
      })
    }
    await getCosPlay()
    this.writeFile(urls)
    return Promise.resolve(`This action returns all willes`)
  }

  findOne(id: number) {
    return `This action returns a #${id} wille`
  }

  update(id: number, updateWilleDto: UpdateWilleDto) {
    return `This action updates a #${id} wille`
  }

  remove(id: number) {
    return `This action removes a #${id} wille`
  }
  writeFile(urls: string[]) {
    urls.forEach(async (url) => {
      try {
        const buffer = await axios.get(url, { responseType: 'stream' }).then((res) => res.data)
        const ws = fs.createWriteStream(join(__dirname, '../../cos/' + new Date().getTime() + '.jpg'))
        if (buffer) {
          buffer.pipe(ws)
        }
      } catch (error) {
        console.log('%c [ error ]-62', 'font-size:13px; background:#7d3359; color:#c1779d;', error)
      }
    })
  }
}
